package utils

import (
	"errors"
	"fmt"
	"net"
	"os"
	"os/exec"
	"strings"
)

// GetLocalIPs 获取所有本地非回环IPv4地址
func GetLocalIPs() ([]string, error) {
	var ips []string

	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return nil, err
	}

	for _, addr := range addrs {
		if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				ips = append(ips, ipnet.IP.String())
			}
		}
	}

	if len(ips) == 0 {
		return nil, errors.New("no local IP address found")
	}

	return ips, nil
}

// getWindowsVersion 获取Windows版本 (不使用golang.org/x/sys/windows)
func GetWindowsVersion() (string, error) {
	// 方法1: 通过systeminfo命令
	cmd := exec.Command("cmd", "/c", "ver")
	output, err := cmd.CombinedOutput()
	if err == nil {
		version := parseWindowsVerOutput(string(output))
		if version != "" {
			return version, nil
		}
	}

	// 方法2: 通过wmic命令 (更可靠)
	cmd = exec.Command("wmic", "os", "get", "Caption,Version,BuildNumber", "/value")
	output, err = cmd.CombinedOutput()
	if err != nil {
		return "", fmt.Errorf("failed to get Windows version: %v", err)
	}

	info := parseWmicOutput(string(output))
	return info["Version"], nil
}

func GetMacOSVersion() (string, error) {
	cmd := exec.Command("sw_vers", "-productVersion")
	output, err := cmd.CombinedOutput()
	if err != nil {
		return "", fmt.Errorf("failed to get macOS version: %v", err)
	}
	return strings.TrimSpace(string(output)), nil
}

// getLinuxVersion 获取Linux版本
func GetLinuxVersion() (string, error) {
	// 尝试读取/etc/os-release文件
	if data, err := os.ReadFile("/etc/os-release"); err == nil {
		info := parseOSRelease(string(data))
		return info["VERSION_ID"], nil
	}

	// 回退到uname命令
	cmd := exec.Command("uname", "-r")
	output, err := cmd.CombinedOutput()
	if err != nil {
		return "", fmt.Errorf("failed to get Linux version: %v", err)
	}

	return strings.TrimSpace(string(output)), nil
}

// parseWindowsVerOutput 解析Windows ver命令输出
func parseWindowsVerOutput(output string) string {
	// 示例输出: Microsoft Windows [版本 10.0.19045.3693]
	start := strings.Index(output, "[版本 ")
	if start == -1 {
		return ""
	}
	start += len("[版本 ")
	end := strings.Index(output[start:], "]")
	if end == -1 {
		return ""
	}
	return output[start : start+end]
}

// parseWmicOutput 解析wmic命令输出
func parseWmicOutput(output string) map[string]string {
	result := make(map[string]string)
	lines := strings.Split(output, "\n")
	for _, line := range lines {
		parts := strings.SplitN(line, "=", 2)
		if len(parts) == 2 {
			key := strings.TrimSpace(parts[0])
			value := strings.TrimSpace(parts[1])
			result[key] = value
		}
	}
	return result
}

// parseOSRelease 解析Linux的/etc/os-release文件
func parseOSRelease(content string) map[string]string {
	result := make(map[string]string)
	lines := strings.Split(content, "\n")
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		parts := strings.SplitN(line, "=", 2)
		if len(parts) == 2 {
			key := parts[0]
			value := strings.Trim(parts[1], `"`)
			result[key] = value
		}
	}
	return result
}
